import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:license_plate_number/license_plate_number.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yurun_smartmerchants/global.dart';
import 'package:yurun_smartmerchants/models/car_add_entity.dart';
import 'package:yurun_smartmerchants/models/car_query_entity.dart';
import 'package:yurun_smartmerchants/models/car_type_entity.dart';
import 'package:yurun_smartmerchants/models/car_detail_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/net/NetUtil.dart';
import 'package:yurun_smartmerchants/res/colours.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:yurun_smartmerchants/utils/evenbus_utils.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';
import 'package:yurun_smartmerchants/utils/StringUtils.dart';

class ApproachEditCar extends StatefulWidget {
  final CarQueryContent carQueryContent;

  ApproachEditCar({Key key, this.carQueryContent});

  @override
  _ApproachEditCarState createState() => _ApproachEditCarState();
}

class _ApproachEditCarState extends State<ApproachEditCar> {
  int consumerId;
  var bus = EventBus();
  final carWeightController = TextEditingController();
  KeyboardController _keyboardController = KeyboardController();
  FocusNode _node = FocusNode();
  String provinceShortName, licencePlate; //车牌
  double tare; //皮重
  int id, vehicleTypeId; //车辆类型
  String typeName; //车辆类型
  List<CarTypeContent> content = new List();
  List<int> listId = List(); //consumerId列表

  @override
  void initState() {
    super.initState();
    String consumer_id = Global.prefs.getString(Global.consumer_id);
    consumerId = int.parse(consumer_id);
    //把consumerId加入里面
    listId.add(consumerId);

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (widget.carQueryContent != null) {
        //因为列表没有车辆类型id所以需要重新调详情接口获取
        getDetail();
      }
      getCarType();
    });
  }

  @override
  void dispose() {
    super.dispose();
    carWeightController.dispose();
    _keyboardController.dispose();
  }

  void getDetail() {
    LoadingUtil.showLoading(context, tip: '加载中...');
    ApiInterface.detailCar(widget.carQueryContent.id).then((value) {
      CarDetailEntity carDetailEntity = CarDetailEntity.fromJson(value);
      setState(() {
        vehicleTypeId = carDetailEntity.typeId;
        typeName = carDetailEntity.typeName;
        id = carDetailEntity.id;
        tare = carDetailEntity.tare;
        provinceShortName = carDetailEntity.provinceShortName;
        licencePlate = carDetailEntity.licencePlate;
        carWeightController.text = tare.toString();
      });
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }

  void getCarType() {
    LoadingUtil.showLoading(context, tip: '加载中...');
    ApiInterface.getVehicleTypes().then((value) {
      setState(() {
        value.forEach((f) => content.add(CarTypeContent.fromJson(f)));
      });
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }

  void addCar() {
    LoadingUtil.showLoading(context, tip: '加载中...');
    ApiInterface.addCar(
            id, provinceShortName, licencePlate, tare, vehicleTypeId, listId)
        .then((value) {
      CarAddEntity carAddEntity = CarAddEntity.fromJson(value);
      if (carAddEntity.success) {
        Navigator.pop(context);
        bus.send("addCar", "");
      }
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('新增车辆',
            style: TextStyle(fontSize: 18, color: Colours.app_words)),
        backgroundColor: Colours.title_bg,
        iconTheme: IconThemeData(color: Colours.app_words),
      ),
      resizeToAvoidBottomPadding: false,
      body: Container(
        color: Colours.gray_ef,
        width: double.infinity,
        height: double.infinity,
        child: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top: AppSize.sp(20)),
              width: double.infinity,
              height: AppSize.sp(98),
              color: Colours.white,
              alignment: Alignment.center,
              child: Row(
                children: <Widget>[
                  Container(
                      margin: EdgeInsets.only(left: AppSize.sp(32)),
                      child: RichText(
                        text: TextSpan(
                          text: '车辆皮重(吨)进场车辆类型',
                          style: TextStyle(
                              color: Colours.color_313131,
                              fontSize: AppSize.sp(32)),
                          children: <TextSpan>[
                            TextSpan(
                                text: ' *',
                                style: TextStyle(
                                    color: Colours.app_main,
                                    fontSize: AppSize.sp(32))),
                          ],
                        ),
                      )),
                  Spacer(),
                  GestureDetector(
                      onTap: () {
                        showModalBottomSheet(
                            context: context,
                            builder: (BuildContext context) {
                              return _showNomalWid(context);
                            });
                      },
                      child: Container(
                          margin: EdgeInsets.only(right: AppSize.sp(12)),
                          child: Text(
                            typeName == null ? "请选择" : typeName,
                            style: typeName == null
                                ? TextStyle(
                                    fontSize: AppSize.sp(32),
                                    color: Colours.color_abacb5)
                                : TextStyle(
                                    fontSize: AppSize.sp(32),
                                    color: Colours.color_313131),
                          ))),
                  Container(
                    margin: EdgeInsets.only(right: AppSize.sp(32)),
                    child: Image.asset(
                      'images/approach_more.png',
                      width: AppSize.width(16),
                      height: AppSize.height(26),
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: AppSize.sp(1)),
              width: double.infinity,
              height: AppSize.sp(98),
              color: Colours.white,
              alignment: Alignment.center,
              child: Stack(
                children: <Widget>[
                  Container(
                      alignment: Alignment(-1, 0),
                      margin: EdgeInsets.only(left: AppSize.sp(32)),
                      child: Text(
                        "车牌号",
                        style: TextStyle(
                            fontSize: AppSize.sp(32),
                            color: Colours.color_313131),
                      )),
                  GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        _node.unfocus();
                      },
                      child: Container(
                          alignment: Alignment.center,
                          margin: EdgeInsets.only(
                              left: AppSize.sp(150), right: AppSize.sp(32)),
                          child: PlateInputField(
                            placeHolder: widget.carQueryContent != null
                                ? widget.carQueryContent.provinceShortName +
                                    widget.carQueryContent.licencePlate
                                : "",
                            styles: PlateStyles.light,
                            inputFieldWidth: 25,
                            keyboardController: _keyboardController,
                            inputFieldHeight: 30,
                            onChanged: (List<String> array, String text) {
                              //普通车牌7位，新能源8位
                              if (text != null && text.length >= 7) {
                                _keyboardController.hideKeyboard();
                                provinceShortName = array[0];
                                licencePlate =
                                    text.substring(1, text.toString().length);
                              } else if (StringUtils.isEmpty(text)) {
                                _keyboardController.hideKeyboard();
                                provinceShortName = "";
                                licencePlate = "";
                              }
                            },
                          ))),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: AppSize.sp(1)),
              width: double.infinity,
              height: AppSize.sp(98),
              color: Colours.white,
              alignment: Alignment.center,
              child: Stack(
                children: <Widget>[
                  Container(
                      alignment: Alignment(-1, 0),
                      margin: EdgeInsets.only(left: AppSize.sp(32)),
                      child: RichText(
                        text: TextSpan(
                          text: '车辆皮重(吨)',
                          style: TextStyle(
                              color: Colours.color_313131,
                              fontSize: AppSize.sp(32)),
                          children: <TextSpan>[
                            TextSpan(
                                text: ' *',
                                style: TextStyle(
                                    color: Colours.app_main,
                                    fontSize: AppSize.sp(32))),
                          ],
                        ),
                      )),
                  Container(
                      margin: EdgeInsets.only(right: AppSize.sp(32)),
                      child: TextField(
                        controller: carWeightController,
                        textAlign: TextAlign.right,
                        style: TextStyle(
                            color: Colours.color_313131,
                            fontSize: AppSize.sp(32)),
                        decoration: InputDecoration(
                            hintText: "输入车辆皮重",
                            border: InputBorder.none,
                            counterText: '',
                            hintStyle: TextStyle(
                                fontSize: AppSize.sp(32),
                                color: Colours.color_abacb5)),
                        onChanged: (value) {
                          tare = double.parse(value.toString());
                        },
                        keyboardType: TextInputType.number,
                        maxLength: 11,
                      )),
                ],
              ),
            ),
            Spacer(),
            GestureDetector(
                onTap: () {
                  if (vehicleTypeId == null) {
                    showToast("请选择车辆类型");
                    return;
                  }
//                  if (provinceShortName == null || licencePlate == null) {
//                    showToast("请输入车牌");
//                    return;
//                  }
                  if (tare == null) {
                    showToast("请输入皮重");
                    return;
                  }
                  addCar();
                },
                child: Container(
                    height: AppSize.height(105),
                    color: Colours.white,
                    child: Container(
                        margin: EdgeInsets.all(AppSize.sp(12)),
                        height: AppSize.height(82),
                        alignment: Alignment.center,
                        decoration: new BoxDecoration(
                          color: Colours.app_main,
                          borderRadius: BorderRadius.all(
                            Radius.circular(AppSize.sp(5)),
                          ),
                        ),
                        child: Container(
                            alignment: Alignment.center,
                            child: Text(
                              "保存",
                              style: TextStyle(
                                  color: Colours.white,
                                  fontSize: AppSize.sp(32)),
                            )))))
          ],
        ),
      ),
    );
  }

  void InputCompleteCallback() {}

  Widget _showNomalWid(BuildContext context) {
    return Container(
        color: Colours.gray_ef,
        child: ListView.builder(
            itemBuilder: (context, index) {
              return getItem(context, index);
            },
            itemCount: content == null ? 0 : content.length));
  }

  Widget getItem(BuildContext context, int index) {
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pop();
        vehicleTypeId = content[index].value;
        setState(() {
          typeName = content[index].label;
        });
      },
      child: Container(
          height: AppSize.height(100),
          color: Colours.white,
          margin: EdgeInsets.only(bottom: AppSize.sp(1)),
          alignment: Alignment.center,
          child: Text(content[index].label)),
    );
  }
}
